package org.algorithm.YaYa.数组.三月.第二周;

import java.util.Arrays;

/**
 * @author YaYa
 * @version 1.0
 * @date 2022/03/0 9:07 PM    星期一的作业
 * @description:
 * <p>
 *     数组中三数相加最接近target
 *     输入：nums = [-1,2,1,-4], target = 1
 *     输出：2
 *     解释：与 target 最接近的和是 2 (-1 + 2 + 1 = 2) 。
 * </p>
 *
 * uri: https://leetcode-cn.com/problems/3sum-closest/solution/hua-jie-suan-fa-16-zui-jie-jin-de-san-shu-zhi-he-b/
 */
public class 最接近的三数之和 {

    public static void main(String[] args) {
        int[] nums = {-1,2,1,-4};
        System.out.println(threeSumClosest(nums, 1));
    }

    public static int threeSumClosest(int[] nums, int target) {
        Arrays.sort(nums);
        int ans = nums[0] + nums[1] + nums[2];
        for(int i=0;i<nums.length;i++) {
            int start = i+1, end = nums.length - 1;
            while(start < end) {
                int sum = nums[start] + nums[end] + nums[i];
                if(Math.abs(target - sum) < Math.abs(target - ans))
                    ans = sum;
                if(sum > target)
                    end--;
                else if(sum < target)
                    start++;
                else
                    return ans;
            }
        }
        return ans;
    }
}
